﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.Utilities;
using NP.BPMReportPlatform.Utils;
using NP.BPMReportPlatform.ZH.Dto;
using SqlSugar;
using Volo.Abp.Application.Dtos;
using static System.Runtime.CompilerServices.RuntimeHelpers;

namespace NP.BPMReportPlatform.ZH
{
    public class ZHService : BPMReportPlatformAppService, IZHService
    {
        private readonly SqlSugarClient _db;
        private readonly SqlSugarClient _dbPlatform;
        private readonly IBPMUtilsAppService _bPMUtilsApp;
        private readonly IBPMPlatformAppService _iBPMPlatformApp;

        public ZHService(ISqlSugarAppService sqlSugarAppService, IBPMUtilsAppService bPMUtilsApp
            , IBPMPlatformAppService iBPMPlatformApp)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _bPMUtilsApp = bPMUtilsApp;
            _iBPMPlatformApp = iBPMPlatformApp;
        }

        public async Task<PagedResultDto<GetPOCAPOutput>> GetAllAsync(GetPOCAPInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x =>
            {
                x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId);
                x.Cycle = x.FinishTime != null ? Math.Round(x.FinishTime.Value.Subtract(x.StartTime).TotalHours, 4).ToString() : "";
            });

            //返回结果
            return new PagedResultDto<GetPOCAPOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        public async Task<List<GetPOCAPOutput>> ExportAsync(GetPOCAPInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            listViewDto.ForEach(x => {
                x.Cycle = x.FinishTime != null ? Math.Round(x.FinishTime.Value.Subtract(x.StartTime).TotalHours, 4).ToString() : "";
            });
            return listViewDto;
        }


        private ISugarQueryable<GetPOCAPOutput> GetQueryable(GetPOCAPInput input)
        {
            var currentUserId = Guid.Empty;
            if (!input.IsQueryAll)
            {
                var currentUserDto = _dbPlatform.Queryable<Users>().Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First();
                if (currentUserDto != null)
                {
                    currentUserId = currentUserDto.UserId;
                }
            }
            var listQueryable = _db.Queryable<POCAPHeader, POCAPHDetail, BusinessProcessesNew>(
                     (x, d, b) => new JoinQueryInfos(JoinType.Inner, x.InstanceNumber == d.InstanceNumber, JoinType.Left, x.InstanceNumber == b.InstanceId))
                .WhereIF(!input.IsQueryAll, x => x.AddUserId.Equals(currentUserId) || x.Approver1Id.Equals(currentUserId))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber), x => x.InstanceNumber == input.InstanceNumber)
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(), (x, d, b) => SqlFunc.ContainsArray(input.OrderStatus.ToArray(), b.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Contains(input.AddUserName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Factory), x => x.Factory.Contains(input.Factory))
                .WhereIF(!string.IsNullOrWhiteSpace(input.PWSCode), (x, d) => d.PWSCode.Contains(input.PWSCode))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                    x => x.AddTime >= input.StartCreationTime && x.AddTime <= input.EndCreationTime)
                .Select((x, d, b) => new GetPOCAPOutput()
                {
                    InstanceNumber = x.InstanceNumber,
                    CreateDateTime = x.AddTime,
                    CreateTime = x.AddTime.ToString(DateFormatHelper.DateTimeFormat),
                    AddUserName = x.AddUserName,
                    OrderStatus = b.ProcessStatusName,
                    PWSCode = d.PWSCode,
                    Factory = d.Factory,
                    ProductCode = d.ProductCode,
                    MaterialCode = d.MaterialCode,
                    MaterialName = d.MaterialName,
                    OriginalAssembly = d.OriginalAssembly,
                    OriginalDescribe = d.OriginalDescribe,
                    Assembly = d.Assembly,
                    Describe = d.Describe,
                    LotNumber = d.LotNumber,
                    OriginalNumber = d.OriginalNumber,
                    AdjustNumber = d.AdjustNumber,
                    AdjustedNumber = d.AdjustedNumber,
                    Unit = d.Unit,
                    WorkProcedure = d.WorkProcedure,
                    Remark = d.Remark,
                    Requirement = d.Requirement,
                    Percentage = d.Percentage,
                    ApplyRemark = d.ApplyRemark,
                    ApprovalRemark = d.ApprovalRemark,
                    ApprovedTime = b.ProcessStatusCode.Equals("approved") ? (b.FinishTime != null ? b.FinishTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "") : "",
                    SyncResult = b.ProcessStatusCode.Equals("approved") ? (x.SyncResult1 ? "成功" : "不完全成功") : b.ProcessStatusName,
                    StartTime = b.StartTime,
                    FinishTime = b.ProcessStatusCode.Equals("approved") ? b.FinishTime : null,
                    SyncError = b.ProcessStatusCode.Equals("approved") ? x.Message1 : "",


                    FormMode = x.FormMode,
                    BatchPwsCode = x.BatchPwsCode,
                    BatchNumber = d.BatchNumber,
                    NewBatchNumber = d.NewBatchNumber,
                    InputNumber = d.InputNumber,
                    CalcNumber = d.CalcNumber,
                    ItemUnit = d.ItemUnit,
                    StorageLocation = d.StorageLocation,
                    ItemBatch = d.ItemBatch,
                    ItemType = d.ItemType,
                    AssemblyType = d.AssemblyType,
                    TotalNumber = d.TotalNumber,
                }).MergeTable().Distinct().OrderBy(ins => ins.CreateDateTime, OrderByType.Desc);
            return listQueryable;
        }



        public async Task<PagedResultDto<GetPWSCodePOCAPOutput>> GetPWSCodeAllAsync(GetPOCAPInput input)
        {
            var listQueryable = GetPWSCodeQueryable(input, out int totalCount);
            var listViewDto = listQueryable.Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize).ToList();
            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);
            listViewDto.ForEach(x =>
            {
                x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId);
                x.DueTime = x.FinishDateTime > x.AddDateTime ?
                    Math.Round(x.FinishDateTime.Value.Subtract(x.AddDateTime).TotalHours, 2) : null;
            });
            //返回结果
            return new PagedResultDto<GetPWSCodePOCAPOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        public async Task<List<GetPWSCodePOCAPOutput>> ExportPWSCodeAsync(GetPOCAPInput input)
        {
            var listQueryable = GetPWSCodeQueryable(input, out _);
            var listViewDto = listQueryable.ToList();
            listViewDto.ForEach(x =>
            {
                x.DueTime = x.FinishDateTime > x.AddDateTime ? 
                    Math.Round(x.FinishDateTime.Value.Subtract(x.AddDateTime).TotalHours, 2) : null;
            });
            return listViewDto;
        }

        private IEnumerable<GetPWSCodePOCAPOutput> GetPWSCodeQueryable(GetPOCAPInput input, out int totalCount)
        {
            var currentUserId = Guid.Empty;
            if (!input.IsQueryAll)
            {
                var currentUserDto = _dbPlatform.Queryable<Users>().Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First();
                if (currentUserDto != null)
                {
                    currentUserId = currentUserDto.UserId;
                }
            }
            var listQueryable = _db.Queryable<POCAPHeader, POCAPHDetail, BusinessProcessesNew, BusinessProcessesNew>(
                     (x, d, b, b1) => new JoinQueryInfos(
                         JoinType.Inner, x.InstanceNumber == d.InstanceNumber, 
                        JoinType.Left, x.InstanceNumber == b.InstanceId,
                        JoinType.Left, x.InstanceNumber == b1.InstanceId))
                .WhereIF(!input.IsQueryAll, x => x.AddUserId.Equals(currentUserId) || x.Approver1Id.Equals(currentUserId))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber), x => x.InstanceNumber == input.InstanceNumber)
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(), (x, d, b) => SqlFunc.ContainsArray(input.OrderStatus.ToArray(), b.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Contains(input.AddUserName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Factory), x => x.Factory.Contains(input.Factory))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                    x => x.AddTime >= input.StartCreationTime && x.AddTime <= input.EndCreationTime)
                .WhereIF(!string.IsNullOrWhiteSpace(input.PWSCode), (x, d, b) => d.PWSCode.Equals(input.PWSCode))
                .Select((x, d, b, b1) => new GetPWSCodePOCAPOutput()
                {
                    InstanceNumber = x.InstanceNumber,
                    InstanceStatus = string.IsNullOrEmpty(b.ProcessStatusName) ? b1.ProcessStatusName : b.ProcessStatusName,
                    InstanceStatusCode = string.IsNullOrEmpty(b.ProcessStatusName) ? b1.ProcessStatusCode : b.ProcessStatusCode,
                    PWSCode = d.PWSCode,
                    Factory = d.Factory,
                    MaterialCode = d.MaterialCode,
                    MaterialName = d.MaterialName,
                    AddUser = x.AddUserName,
                    //AddTime = SqlFunc.AggregateMin(x.AddTime).ToString(DateFormatHelper.DateTimeFormat),
                    AddDateTime = x.AddTime,
                    FinishDateTime = (b.FinishTime == null || b.FinishTime == DateTime.MinValue) ? b1.FinishTime : b.FinishTime,
                    //FinishTime = b.FinishTime != null ? b.FinishTime.Value.ToString(DateFormatHelper.DateTimeFormat) : "",
                    //RequestCount = SqlFunc.AggregateCount(d.PWSCode),
                    LastResult = (b.FinishTime == null || b.FinishTime == DateTime.MinValue) &&
                        (b1.FinishTime == null || b1.FinishTime == DateTime.MinValue) ? "" :
                         SqlFunc.IIF(x.SyncResult1 || (!string.IsNullOrEmpty(x.Message1) && !x.Message1.Contains(d.PWSCode)), "成功", "失败")
                }).ToList();
            var res = listQueryable.GroupBy(x => x.PWSCode)
                .Select(x => new GetPWSCodePOCAPOutput
                {
                    InstanceNumber = 
                        x.Where(q => q.InstanceStatusCode == "approved").OrderByDescending(q => q.FinishDateTime).FirstOrDefault()?.InstanceNumber ??
                        x.OrderByDescending(q => q.FinishDateTime).FirstOrDefault().InstanceNumber,
                    InstanceStatus =
                        x.Where(q => q.InstanceStatusCode == "approved").OrderByDescending(q => q.FinishDateTime).FirstOrDefault()?.InstanceStatus ??
                        x.OrderByDescending(q => q.FinishDateTime).FirstOrDefault().InstanceStatus,
                    PWSCode =
                        x.Where(q => q.InstanceStatusCode == "approved").OrderByDescending(q => q.FinishDateTime).FirstOrDefault()?.PWSCode ??
                        x.OrderByDescending(q => q.FinishDateTime).FirstOrDefault().PWSCode,
                    Factory =
                        x.Where(q => q.InstanceStatusCode == "approved").OrderByDescending(q => q.FinishDateTime).FirstOrDefault()?.Factory ??
                        x.OrderByDescending(q => q.FinishDateTime).FirstOrDefault().Factory,
                    MaterialCode =
                        x.Where(q => q.InstanceStatusCode == "approved").OrderByDescending(q => q.FinishDateTime).FirstOrDefault()?.MaterialCode ??
                        x.OrderByDescending(q => q.FinishDateTime).FirstOrDefault().MaterialCode,
                    MaterialName =
                        x.Where(q => q.InstanceStatusCode == "approved").OrderByDescending(q => q.FinishDateTime).FirstOrDefault()?.MaterialName ??
                        x.OrderByDescending(q => q.FinishDateTime).FirstOrDefault().MaterialName,
                    AddUser = x.OrderBy(q => q.AddDateTime).FirstOrDefault().AddUser,
                    AddDateTime = x.OrderBy(q => q.AddDateTime).FirstOrDefault().AddDateTime,
                    AddTime = x.OrderBy(q => q.AddDateTime).FirstOrDefault().AddDateTime.ToString(DateFormatHelper.DateTimeFormat),
                    FinishDateTime = x.Where(q => q.InstanceStatusCode == "approved").OrderByDescending(q => q.FinishDateTime).FirstOrDefault()?.FinishDateTime,
                    FinishTime = x.Where(q => q.InstanceStatusCode == "approved").OrderByDescending(q => q.FinishDateTime).FirstOrDefault()?.FinishDateTime?.ToString(DateFormatHelper.DateTimeFormat) ?? "",
                    RequestCount = x.Select(q => q.InstanceNumber).Distinct().Count(),
                    LastResult = x.Where(q => q.InstanceStatusCode == "approved").OrderByDescending(q => q.FinishDateTime).FirstOrDefault()?.LastResult,
                });
            totalCount = listQueryable.GroupBy(x => x.PWSCode).Count();
            return res.OrderByDescending(x => x.FinishDateTime);
        }

        #region TU产地变更申请审批流程
        public async Task<PagedResultDto<GetTUDCBGSQOutput>> GetAllAsync(GetTUDCBGSQInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input, "seach");
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);
            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);
            listViewDto.ForEach(x =>
            {
                x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId);
            });

            //返回结果
            return new PagedResultDto<GetTUDCBGSQOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        public async Task<List<GetTUDCBGSQOutput>> ExportAsync(GetTUDCBGSQInput input)
        {
            var listQueryable = GetQueryable(input,"export");
            var listViewDto = await listQueryable.ToListAsync();
            return listViewDto;
        }


        private ISugarQueryable<GetTUDCBGSQOutput> GetQueryable(GetTUDCBGSQInput input,string type)
        {
            var currentUserId = Guid.Empty;
            if (!input.IsQueryAll)
            {
                var currentUserDto = _dbPlatform.Queryable<Users>().Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First();
                if (currentUserDto != null)
                {
                    currentUserId = currentUserDto.UserId;
                }
            }
            var listQueryable = _db.Queryable<TUDCBGSQHeader, BusinessProcessesNew>(
                               (x, b) => new JoinQueryInfos(JoinType.Inner, x.InstanceNumber == b.InstanceId))
                          .WhereIF(!input.IsQueryAll, x => x.AddUserId.Equals(currentUserId))
                          .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber), x => x.InstanceNumber == input.InstanceNumber)
                          .WhereIF(!input.OrderStatus.IsNullOrEmpty(), (x, b) => SqlFunc.ContainsArray(input.OrderStatus.ToArray(), b.ProcessStatusCode))
                          .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Contains(input.AddUserName))
                          .WhereIF(!string.IsNullOrWhiteSpace(input.Gyljfzx), x => x.Gyljfzx.Contains(input.Gyljfzx))
                          .WhereIF(!string.IsNullOrWhiteSpace(input.CurrentFactory), x => x.CurrentFactory.Contains(input.CurrentFactory) || x.CurrentFactoryName.Contains(input.CurrentFactory))
                          .WhereIF(!string.IsNullOrWhiteSpace(input.OpenFactory), x => x.OpenFactory.Contains(input.OpenFactory) || x.OpenFactoryName.Contains(input.OpenFactory))
                          .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null, x => x.AddTime >= input.StartCreationTime && x.AddTime <= input.EndCreationTime)
                          .Select((x, b) => new GetTUDCBGSQOutput()
                          {
                              InstanceNumber = x.InstanceNumber,
                              ProcessStartTime = x.AddTime,
                              AddUserName = x.AddUserName,
                              OrderStatus = b.ProcessStatusName,
                              Jjcd = x.Jjcd,
                              Gyljfzx = x.Gyljfzx,
                              CurrentFactory = x.CurrentFactory,
                              CurrentFactoryName = x.CurrentFactoryName,
                              OpenFactory = x.OpenFactory,
                              OpenFactoryName = x.OpenFactoryName,
                              Requirement = x.Requirement,
                              TotalQuantity = x.TotalQuantity
                          }).MergeTable().Distinct().OrderBy(x => x.ProcessStartTime, OrderByType.Desc);
            if (type == "export")
            {
                listQueryable = _db.Queryable<TUDCBGSQHeader, TUDCBGSQDetail1, BusinessProcessesNew>(
                    (x, d, b) => new JoinQueryInfos(JoinType.Inner, x.InstanceNumber == d.InstanceNumber, JoinType.Left, x.InstanceNumber == b.InstanceId))
               .WhereIF(!input.IsQueryAll, x => x.AddUserId.Equals(currentUserId))
               .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber), x => x.InstanceNumber == input.InstanceNumber)
               .WhereIF(!input.OrderStatus.IsNullOrEmpty(), (x, d, b) => SqlFunc.ContainsArray(input.OrderStatus.ToArray(), b.ProcessStatusCode))
               .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Contains(input.AddUserName))
               .WhereIF(!string.IsNullOrWhiteSpace(input.Gyljfzx), x => x.Gyljfzx.Contains(input.Gyljfzx))
               .WhereIF(!string.IsNullOrWhiteSpace(input.CurrentFactory), x => x.CurrentFactory.Contains(input.CurrentFactory) || x.CurrentFactoryName.Contains(input.CurrentFactory))
               .WhereIF(!string.IsNullOrWhiteSpace(input.OpenFactory), x => x.OpenFactory.Contains(input.OpenFactory) || x.OpenFactoryName.Contains(input.OpenFactory))
               .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null, x => x.AddTime >= input.StartCreationTime && x.AddTime <= input.EndCreationTime)
               .Select((x, d, b) => new GetTUDCBGSQOutput()
               {
                   InstanceNumber = x.InstanceNumber,
                   ProcessStartTime = x.AddTime,
                   AddUserName = x.AddUserName,
                   OrderStatus = b.ProcessStatusName,
                   Jjcd = x.Jjcd,
                   Gyljfzx = x.Gyljfzx,
                   CurrentFactory = x.CurrentFactory,
                   CurrentFactoryName = x.CurrentFactoryName,
                   OpenFactory = x.OpenFactory,
                   OpenFactoryName = x.OpenFactoryName,
                   Requirement = x.Requirement,
                   TotalQuantity = x.TotalQuantity,
                   SortNo = d.SortNo,
                   BusinessGroup = d.BusinessGroup,
                   MaterielCode = d.MaterielCode,
                   MaterielName = d.MaterielName,
                   Specs = d.Specs,
                   Province = d.Province,
                   SalesDept = d.SalesDept,
                   City = d.City,
                   DemandNumber = d.DemandNumber,
                   DemandWeight = d.DemandWeight,
                   T09Code = d.T09Code,
                   T09Desc = d.T09Desc,
                   Remark = d.Remark
               }).MergeTable().Distinct().OrderBy(x => x.ProcessStartTime, OrderByType.Desc).OrderBy(x => x.SortNo);
            }
            return listQueryable;
        }
        #endregion
        
        #region IU分析委托流程
        public async Task<PagedResultDto<GetIUFXWTLCOutput>> GetAllAsync(GetIUFXWTLCInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);
            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);
            listViewDto.ForEach(x =>
            {
                x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId);
               x.SampleName= _db.Queryable<IUCommissionedAnalysisProcessDetail>().Where(u => u.InstanceNumber == x.InstanceNumber).Select(u => u.TestSampleName).ToList()?.JoinAsString(",");
               x.InstrumentName= _db.Queryable<IUCommissionAnalysisTestItemsDetail>().Where(u => u.InstanceNumber == x.InstanceNumber).Select(u => u.Name).ToList()?.JoinAsString(",");
            });

            //返回结果
            return new PagedResultDto<GetIUFXWTLCOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        public async Task<List<GetIUFXWTLCOutput>> ExportAsync(GetIUFXWTLCInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            listViewDto.ForEach(x =>
            {
                x.SampleName = _db.Queryable<IUCommissionedAnalysisProcessDetail>().Where(u => u.InstanceNumber == x.InstanceNumber).Select(u => u.TestSampleName).ToList()?.JoinAsString(",");
                x.InstrumentName = _db.Queryable<IUCommissionAnalysisTestItemsDetail>().Where(u => u.InstanceNumber == x.InstanceNumber).Select(u => u.Name).ToList()?.JoinAsString(",");
            });
            return listViewDto;
        }


        private ISugarQueryable<GetIUFXWTLCOutput> GetQueryable(GetIUFXWTLCInput input)
        {
            var currentUserId = Guid.Empty;
            if (!input.IsQueryAll)
            {
                var currentUserDto = _dbPlatform.Queryable<Users>().Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First();
                if (currentUserDto != null)
                {
                    currentUserId = currentUserDto.UserId;
                }
            }
            var listQueryable = _db.Queryable<IUCommissionedAnalysisProcessHeader, BusinessProcessesNew>(
                     (x, b) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == b.InstanceId))
                .WhereIF(!input.IsQueryAll, x => x.AddUserId.Equals(currentUserId))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber), x => x.InstanceNumber == input.InstanceNumber)
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(), (x, b) => SqlFunc.ContainsArray(input.OrderStatus.ToArray(), b.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Contains(input.AddUserName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Address), x => x.Address.Contains(input.Address))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null, x => x.AddTime >= input.StartCreationTime && x.AddTime <= input.EndCreationTime)
                .Select((x, b) => new GetIUFXWTLCOutput()
                {
                    InstanceNumber = x.InstanceNumber,
                    ProcessStartTime = x.AddTime,
                    AddUserName = x.AddUserName,
                    OrderStatus = b.ProcessStatusName,
                    Address = x.Address,
                    InternalNumber = x.InternalNumber,
                    CostCenter = x.CostCenter,
                    DelegatorUserName = x.DelegatorUserName,
                    PhoneNumber = x.PhoneNumber,
                    DelegatorEmail = x.DelegatorEmail,
                    AnalysisCost = x.AnalysisCost,
                    BackgroundPurpose = x.BackgroundPurpose,
                    CcUsersName = x.CcUsersName
                }).MergeTable().Distinct().OrderBy(ins => ins.ProcessStartTime, OrderByType.Desc);
            return listQueryable;
        }
        #endregion
    }
}